import TextArea from "antd/es/input/TextArea"
import lessModule from "./index.module.less"
import { DatePicker, Divider, Form, FormInstance, Input, InputNumber, Select, Space, Upload } from "antd"
import HomePage_SingleBtnComponent from "../../../singleBtn"
import { Fragment, useEffect, useRef, useState } from "react"
import uploadFileImage from "../../../../../../assets/image/homePage-uploadFile.png"
import HomePage_MapComponent from "../../../map"
import { ReactComponent as FiveOneOnOneSvg } from '../../../../../../assets/svg/500OneOnOne.svg'
import { ReactComponent as TwoOneOnOneSvg } from '../../../../../../assets/svg/220OneOnOne.svg'
import { ReactComponent as TwoOneToMany } from '../../../../../../assets/svg/220OneToMany.svg'
import { $eventBus, $EventBus_off, $EventBus_on, $selectOptionData } from "../../../../../../common/utils"
import HomePage_MultipleBtnComponent from "../../../multipleBtn"
import L, { LatLngExpression } from "leaflet"
import HomePage_ModalComponent from "../.."
import HomePage_ModalComponent_ConfirmationModallComponent from "../confirmationModal"
import dayjs from 'dayjs';
import HomePage_DateTimePickerRangeComponent from "../../../dateTimePickerRange"
interface componentInterface {
    form: FormInstance,
    type: string
    isHorizontal?: boolean
    gapX?: number
    gapY?: number
    formItemList: Array<object>
    sourceData?: object
    errLineList?: Array<string>
    uploadImageData?: object
    change_value?: Function
    change_mainOptionList?: Function
    change_connectMethodOptionList?: Function
}
// 主页-弹窗组件-表单组件
const HomePage_ModalComponent_NormalFormComponent: React.FC<componentInterface> = (props) => {
    const imagextensionNameList = [".png", ".jpg"]

    let [singleBtnSelectedValue, setSingleBtnSelectedValue] = useState<string>("")
    const [multipleBtnSelectedList, setMultipleBtnSelectedList] = useState<Array<string>>([])
    const [isMainCountModal, setIsMainCountModal] = useState<boolean>(false)
    const mainCountLast = useRef<number>(0)
    const [multipleBtnSelectedOtherList, setMultipleBtnSelectedOtherList] = useState<Array<object | number>>([])
    const [connectSVG, setConnectSvg] = useState<any>(null)
    const [lineList, setLineList] = useState<Array<string>>([])
    const [dataTypeList, setDataTypeList] = useState<Array<string>>([])
    const [mapFuncData, setMapFuncData] = useState<object>({})
    const [base64Image, setBase64Image] = useState<string>('');
    const [sourceData, setSourceData] = useState<object>({})
    const substationMarker = useRef<L.Marker>()

    const mapMarker_substation = (map: L.Map) => {
        substationMarker.current && map.removeLayer(substationMarker.current)

        if (props.form.getFieldValue("longitude") && props.form.getFieldValue("latitude")) {
            const positionList: LatLngExpression = [props.form.getFieldValue("latitude"), props.form.getFieldValue("longitude")]
            substationMarker.current = L.marker(positionList, {
                icon: L.divIcon({
                    html: `<div class=${lessModule["homePageModalComponentNormalFormComponent-item__substation"]}></div>`,
                })
            }).addTo(map)
            map.setView(positionList, 15)
        }
    }

    const update_formMapFuncData = (key: string, func: Function) => {
        const isRefreshKeyList = ["substationMarker"]
        mapFuncData[key] = {
            isRefresh: isRefreshKeyList.includes(key),
            func
        }
        setMapFuncData({ ...mapFuncData })
    }

    const change_line = (list: Array<string>, isRepeat = true) => {
        // 只会在自动生成时执行
        const repeatData = {}
        isRepeat && list.forEach((item: string, idx: number) => {
            repeatData[item] ??= -1
            const repeatList = list.filter((filterItem: string) => !item.includes("_") && filterItem.split("_")[0] === item)
            if (repeatList.length) {
                repeatData[item] += 1
                if (repeatData[item] > 0) {
                    const suffix = Math.max(...repeatList.map((item: string) => parseInt(item.split("_")[1] ?? 0))) + 1
                    list[idx] += `_${suffix}`

                }
            }
            dataTypeList[idx] = $selectOptionData["dataType"][0]["label"]
            setDataTypeList([...dataTypeList])
        })
        props.form.setFieldValue("line", list)
        props.form.setFieldValue("dataType", dataTypeList)
    }

    const change_svg = () => {
        setConnectSvg(
            props.form.getFieldValue("volLevel") === "220kV" ? props.form.getFieldValue("connectMethod") === "一对一" ? <TwoOneOnOneSvg />

                : props.form.getFieldValue("connectMethod") === "一对多" && <TwoOneToMany />

                : props.form.getFieldValue("volLevel") === "500kV" && props.form.getFieldValue("connectMethod") === "一对一" && <FiveOneOnOneSvg />
        )
    }

    const change_form = (data: object) => {
        // 站点经纬度
        ["longitude", "latitude"].includes(Object.keys(data)[0]) && update_formMapFuncData("substationMarker", mapMarker_substation)
        // 接线方式
        "connectMethod" in data && change_svg()
        // 主变台数
        if ("mainCount" in data) {
            data["mainCount"] ??= 0
            mainCountLast.current ? setIsMainCountModal(true) :
                setTimeout(() => {
                    $eventBus.emit("confirmOperation", { source: "HomePage_ModalComponent_NormalFormComponent", explain: "已修改主变台数,请执行", data: { type: "mainCount" } })
                })
        }

        // 站点名称
        "stationName" in data && props.form.getFieldValue("connecSiteName")?.length && "line" in props.form.getFieldsValue() && change_line(props.form.getFieldValue("stationName") ? props.form.getFieldValue("connecSiteName").map((item: string) => `${props.form.getFieldValue("stationName")[0]}${item.split("kV")[1][0]}线`) : [])

        props?.change_value?.(data)
    }

    const change_multipleBtnSelectedList = (data: object) => {
        props.form.setFieldValue("connecSiteName", [...data["selectedList"]])
        props.form.setFieldValue("connecSite", [...data["selectedOtherList"].map((item: object | number) => typeof (item) === "number" ? item : item["id"])])
        props.form.getFieldValue("stationName") && "line" in props.form.getFieldsValue() && change_line(props.form.getFieldValue("stationName") ? props.form.getFieldValue("connecSiteName").map((item: string) => `${props.form.getFieldValue("stationName")[0]}${item.split("kV")[1][0]}线`) : [])
        setMultipleBtnSelectedList([...data["selectedList"]])
        setMultipleBtnSelectedOtherList([...data["selectedOtherList"]])
    }

    const init_labelColor = () => {
        if (props.type === "see") {
            const labelDomList = document.querySelectorAll('.ant-form-item .ant-form-item-label >label')
            labelDomList.forEach((item: any) => {
                item.style.color = "rgba(0, 0, 0, 0.45)"
            })
        }
    }

    const change_mainCountModalCancel = () => {
        props.form.setFieldValue("mainCount", mainCountLast.current)
        props.form.validateFields(["mainCount"])
        setIsMainCountModal(false)
    }

    // 上传
    const beforeUpload_image = (file: any, key: string) => {
        const reader = new FileReader();
        // 读取文件并转换为 Base64
        reader.onload = (e: any) => {
            const base64 = e.target.result;
            props.form.setFieldValue(key, base64)
            setBase64Image(base64); // 将 Base64 数据保存到状态
        };
        reader.readAsDataURL(file); // 开始读取文件

        // 阻止默认上传行为
        return false;


    }
    const change_rangePicker = (key: string, dateStringList: Array<string>) => {
        props.form.setFieldValue(key, dateStringList)
    }
    // 广播函数数据
    const eventBusFuncData = {
        selectMonitorModalSelectedList: (data) => {
            switch (data["data"]["mode"]) {
                case "single":
                    singleBtnSelectedValue = data["data"]["selectedList"][0];
                    const selectedOtherData = data["data"]["selectedOtherList"][0];
                    ["stationName"].forEach((item: string) => {
                        if (item in props.form.getFieldsValue()) {
                            props.form.setFieldValue(item, singleBtnSelectedValue)
                            if (item === "stationName") {
                                // 巡维中心
                                "maintainCentre" in props.form.getFieldsValue() && props.form.setFieldValue("maintainCentre", selectedOtherData?.["maintainCentre"])
                                // 电压等级
                                "volLevel" in props.form.getFieldsValue() && props.form.setFieldValue("volLevel", selectedOtherData?.["volLevel"])
                                // 安装主变
                                "monitorMain" in props.form.getFieldsValue() && props.change_mainOptionList?.(selectedOtherData?.["groundPoint"].map((item:string)=>{return {label:item}}))
                                // 接线方式
                                "stationName" in props.form.getFieldsValue() && props.form.setFieldValue("stationID", selectedOtherData?.["id"])
                                if ("connectMethod" in props.form.getFieldsValue()) {
                                    props.form.setFieldValue("connectMethod", null)
                                    props.change_connectMethodOptionList?.(props.form.getFieldValue("volLevel") === "220kV" ? [{ label: "一对一" }, { label: "一对多" }] : [{ label: "一对一" }])
                                }
                                // 手动触发 singleBtn 的校验
                                props.form.validateFields(["stationName"])
                            }
                        }
                    })
                    setSingleBtnSelectedValue(singleBtnSelectedValue)
                    break;
                case "multiple":
                    change_multipleBtnSelectedList(data["data"])
                    break;
            }
        },

        // 确认操作（确认修改主变台数）
        confirmOperation: (data: object) => {
            const alterMainCount = (props.form.getFieldValue("mainCount") ?? 0) - (props.sourceData?.["mainCount"] ?? 0)
            const mainList = (props.sourceData?.["main"] ?? []).sort((a: string, b: string) => parseInt(a) - parseInt(b))
            let optionList: Array<string> = []
            if (props.type === "add") {
                optionList = Array.from({ length: alterMainCount }, (_, i) => (i + 1).toString())
                props.form.setFieldValue("main", optionList)
            } else {
                if (alterMainCount > 0) {
                    let addMainCount = 0
                    const alterMainList: Array<string> = []
                    Array.from({ length: (props.form.getFieldValue("mainCount") ?? 0) }, (_, i) => i + 1).forEach((item: number) => {
                        if (addMainCount < alterMainCount && !mainList.includes(item.toString())) {
                            alterMainList.push(item.toString())
                            addMainCount += 1
                        }
                    })
                    optionList = [...mainList, ...alterMainList].sort((a: string, b: string) => parseInt(a) - parseInt(b))
                    props.form.setFieldValue("main", alterMainList)
                }
                else if (alterMainCount === 0) {
                    props.form.setFieldValue("main", [])
                    optionList = mainList
                }
                else {
                    optionList = [...mainList]
                    props.form.setFieldValue("main", optionList.splice(alterMainCount))
                }
            }

            const mainOptionList = optionList.map((item: string) => { return { label: `#${item}` } });
            if (optionList.length) {
                props.form.setFieldValue("monitorMain", (props.form.getFieldValue("monitorMain") ?? []).filter((item: string) => optionList.map((item: string) => `#${item}`).includes(item)))
                props.form.setFieldValue("showMain", optionList.map((item: string) => `#${item}`).includes(props.form.getFieldValue("showMain")) ? props.form.getFieldValue("showMain") : null)
                props.form.setFieldValue("groundPoint", (props.form.getFieldValue("groundPoint") ?? []).filter((item: string) => optionList.map((item: string) => `#${item}`).includes(item)))
            }
            else {
                props.form.setFieldValue("monitorMain", [])
                props.form.setFieldValue("showMain", null)
                props.form.setFieldValue("groundPoint", [])
            }
            alterMainCount && props.change_mainOptionList?.(mainOptionList)

            mainCountLast.current = props.form.getFieldValue("mainCount")
            setIsMainCountModal(false)
        },
    }

    const init_form = () => {
        props.form.setFieldsValue(props.sourceData)
        if (props.sourceData && "connecSiteName" in props.sourceData && "connecSite" in props.sourceData && "line" in props.sourceData) {
            setMultipleBtnSelectedList([...(props.sourceData["connecSiteName"] as Array<string>)])
            setMultipleBtnSelectedOtherList([...(props.sourceData["connecSite"] as Array<object | number>)])
            setLineList([...(props.sourceData["line"] as Array<string>)])
            setDataTypeList([...(props.sourceData["dataType"] as Array<string>)])
        }

        if ("connectMethod" in props.form.getFieldsValue()) {
            change_svg()
        }
        if ("mainCount" in props.form.getFieldsValue()) {
            mainCountLast.current = props.form.getFieldValue("mainCount") ?? 0
        }
        setSourceData({ ...props.sourceData })
    }


    useEffect(() => {
        init_form()
    }, [props.sourceData])

    useEffect(() => {
        props.errLineList?.length && change_line(props.errLineList ?? props.form.getFieldValue("line"), false)
    }, [props.errLineList])

    useEffect(() => {
        init_labelColor()
        $EventBus_on(eventBusFuncData)
        update_formMapFuncData("substationMarker", mapMarker_substation)
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])

    return (
        <Form
            className={lessModule["homePageModalComponentNormalFormComponent"]}
            style={{ gap: `${props.gapY ?? 0}px ${props.gapX ?? 24}px` }}
            form={props.form}
            layout={props.type === "see" || props.isHorizontal ? "horizontal" : "vertical"}
            onValuesChange={change_form}>
            {
                props.formItemList.map((item, idx) => (
                    <Fragment key={`formItemItem${idx}`}>
                        {
                            props.type !== "see" && item["key"] === "line" ?
                                <>
                                    <div className={lessModule["homePageModalComponentNormalFormComponent-label"]}> 关联线路（自动生成）</div>

                                    <div className={lessModule["homePageModalComponentNormalFormComponent-line"]}>
                                        <Form.List name="line">
                                            {(fields) => (
                                                <div className={lessModule["homePageModalComponentNormalFormComponent-line__column"]}>
                                                    {
                                                        (props.form.getFieldValue("line") || lineList).map((item: string, idx: number) => (
                                                            <div key={`lineName${idx}`} className={lessModule["line-column__card"]} style={{ padding: "8px 13px 8px 8px",marginTop:idx ? 8 : 0 }}>
                                                                <div className={lessModule["column-card__group"]}>
                                                                    <div className={lessModule["card-group__label"]}>线路名称</div>
                                                                    <Form.Item
                                                                        className={lessModule["homePageModalComponentNormalFormComponent-item"]}
                                                                        style={{
                                                                            width: "100%",
                                                                            marginBottom: 8,
                                                                        }}
                                                                        name={[idx]}
                                                                        rules={[{ required: true, message: '请输入' }, ({ getFieldValue }: any) => ({
                                                                            validator(rule: any, value: string) {
                                                                                const fieldIdx = parseInt(rule["field"].split(".")[1])
                                                                                if (value) {
                                                                                    if (!(/^(?!.*__).*_$|^(?!.*__).*$/.test(value))) {
                                                                                        return Promise.reject(new Error("最多只能出现一个“_”"));
                                                                                    } else if (!(/^[^_]*(_\d+)?$/.test(value))) {
                                                                                        return Promise.reject(new Error("“_”后面只能是数字"));
                                                                                    } else if (getFieldValue("line").filter((item: object, idx: number) => idx !== fieldIdx).includes(value)) {
                                                                                        return Promise.reject(new Error("线路名称重复"));
                                                                                    }
                                                                                }
                                                                                return Promise.resolve();
                                                                            },
                                                                        }),
                                                                        ]}
                                                                    >
                                                                        <Input placeholder="请输入" />
                                                                    </Form.Item>
                                                                </div>
                                                            </div>
                                                        ))
                                                    }
                                                </div>
                                            )}
                                        </Form.List>
                                        <Form.List name="dataType">
                                            {(fields) => (
                                                <div className={lessModule["homePageModalComponentNormalFormComponent-line__column"]}>
                                                    {
                                                        (props.form.getFieldValue("dataType") || dataTypeList).map((item: string, idx: number) => (
                                                            <div key={`dataType${idx}`} className={lessModule["line-column__card"]} style={{ padding: "8px 8px 8px 13px",marginTop:idx ? 8 : 0  }}>
                                                                <div className={lessModule["column-card__group"]}>
                                                                    <div className={lessModule["card-group__label"]}>流动路径</div>
                                                                    <Form.Item
                                                                        className={lessModule["homePageModalComponentNormalFormComponent-item"]}
                                                                        style={{
                                                                            width: "100%",
                                                                            marginBottom: 8,
                                                                        }}
                                                                        name={[idx]}
                                                                        rules={[{ required: true, message: '请选择' }]}
                                                                    >
                                                                        <Select  options={$selectOptionData["dataType"].slice(0,3)} fieldNames={{ value: "label" }} />
                                                                    </Form.Item>
                                                                </div>
                                                            </div>
                                                        ))
                                                    }
                                                </div>
                                            )}
                                        </Form.List>

                                    </div>
                                </>
                                :
                                <Form.Item

                                    className={lessModule["homePageModalComponentNormalFormComponent-item"]}
                                    style={{
                                        width: item["width"] ?? "calc((100% - 24px) / 2)",
                                        marginBottom: ["topic"].includes(item["type"]) ? 16 : props.type === "see" ? 22 : ["title"].includes(item["type"]) ? 8 : 24,
                                        display: item["hide"] && "none"
                                    }}
                                    colon={false}
                                    label={item["label"] ? <span style={{ color: sourceData["editField"]?.includes(item["key"]) ? '#D54941' : 'rgba(0, 0, 0, 0.65)' }}>{item["label"]}{item["label"] && "："}</span> : false}
                                    name={item["key"]}
                                    rules={[{ required: props.type !== "see" && !(item["key"] === "connectMethod" && props.form.getFieldValue("volLevel") === "110kV") && item["isRequire"], message: item["placeholder"] }]}
                                >

                                    {

                                        item["type"] === "map" ?
                                            <HomePage_MapComponent styleData={item["styleData"] ?? []} funcList={Object.values(mapFuncData)} />
                                            :
                                            item["type"] === "svg" ? <div className={lessModule["homePageModalComponentNormalFormComponent-item__svg"]}>
                                                {
                                                    props.form.getFieldValue("connectMethod") ? connectSVG : <span>未选择接线方式</span>
                                                }

                                            </div>
                                                :
                                                item["type"] === "title" ? <>
                                                    <div className={lessModule["homePageModalComponentNormalFormComponent-item__bigTitle"]}>{item["bigTitle"]}</div>
                                                    <Divider>{item["smallTitle"]}</Divider>
                                                </>
                                                    :
                                                    item["type"] === "uploadImage" ?
                                                        <Upload accept={""} fileList={[]} beforeUpload={(file) => beforeUpload_image(file, item["key"])}>
                                                            <div className={lessModule["homePageModalComponentNormalFormComponent-item__uploadImage"]} style={{ borderWidth: props.form.getFieldValue(item["key"]) ? 1 : 0 }}>
                                                                {

                                                                    props.form.getFieldValue(item["key"]) ? <img className={lessModule["item-uploadImage__image"]} src={props.form.getFieldValue(item["key"]) || base64Image} />
                                                                        : <div className={lessModule["item-uploadImage__upload"]}>
                                                                            <img src={uploadFileImage} />
                                                                            <div className={lessModule["uploadImage-upload__label"]}>击或将文件拖拽到这里上传</div>
                                                                            <span>支持扩展名：{imagextensionNameList.join(" ")}</span>
                                                                        </div>
                                                                }
                                                            </div>

                                                        </Upload> :
                                                        (props.type === "add" || props.type === "edit") ? <>
                                                            {
                                                                item["type"] === "input" && <Input placeholder={item["placeholder"]} disabled={item["isDisabled"]} autoComplete="off" />
                                                            }
                                                            {
                                                                (item["type"] === "select" || item["type"] === "multipleSelect") && <Select showSearch mode={item["type"] === "multipleSelect" ? "multiple" : undefined} options={item["optionList"]} placeholder={item["placeholder"]} fieldNames={{ value: "label" }} />
                                                            }
                                                            {
                                                                item["type"] === "inputNumber" && <InputNumber min={item["min"] ?? undefined} max={item["max"] ?? undefined} placeholder={item["placeholder"]} precision={item["precision"] ?? undefined} autoComplete="off" />
                                                            }
                                                            {
                                                                item["type"] === "datePicker" && <DatePicker format="YYYY-MM-DD HH:mm" showTime />
                                                            }
                                                            {
                                                                item["type"] === "dateTimePickerRange" && <HomePage_DateTimePickerRangeComponent isHideInit width={380} format={item["format"]} change_rangePicker={(dateStringList: Array<string>) => change_rangePicker(item["key"], dateStringList)} />
                                                            }
                                                            {
                                                                item["type"] === "textArea" && <TextArea rows={item["row"]} placeholder={item["placeholder"]} />
                                                            }
                                                            {
                                                                item["type"] === "singleBtn" && <HomePage_SingleBtnComponent selectedValue={singleBtnSelectedValue || props.form.getFieldValue(item["key"])} minWidth={120} monitoringType={item["monitoringType"]} monitorModalName={item["monitorModalName"]} />
                                                            }
                                                            {
                                                                item["type"] === "multipleBtn" && <HomePage_MultipleBtnComponent minWidth={120} stationData={props.type === "add" ? {} : props.sourceData} selectedList={multipleBtnSelectedList} selectedOtherList={multipleBtnSelectedOtherList} monitoringType={item["monitoringType"]} monitorModalName={item["monitorModalName"]} change_selectedList={change_multipleBtnSelectedList} />
                                                            }

                                                        </>

                                                            :
                                                            <>
                                                                {
                                                                    ["monitorMain", "groundPoint", "line"].includes(item["key"]) ?
                                                                        <span style={{ color: sourceData["editField"]?.includes(item["key"]) ? '#D54941' : 'rgba(0, 0, 0, 0.85)' }}>{props.form.getFieldValue(item["key"])?.join("、")}</span>

                                                                        :
                                                                        item["type"] === "topic" ? <div className={lessModule["homePageModalComponentNormalFormComponent-item__topic"]}>{item["topic"]}</div>
                                                                            :



                                                                            (item["type"] === "relatedRoutes" && props.form.getFieldValue("substationName")) ? <span className={lessModule["homePageModalComponentNormalFormComponent-item__relatedRoutes"]}>
                                                                                {
                                                                                    props.form.getFieldValue("directConnectionSubstation").length && props.form.getFieldValue("directConnectionSubstation").map((item: string) => `${props.form.getFieldValue("substationName")[0]}${item[0][0]}线`).join("、")
                                                                                }
                                                                            </span>
                                                                                : !["map"].includes(item["type"]) && <span style={{ color: sourceData["editField"]?.includes(item["key"]) ? '#D54941' : 'rgba(0, 0, 0, 0.85)' }}> {Array.isArray(sourceData[item["key"]]) ? sourceData[item["key"]].join("、") : sourceData[item["key"]]}</span>
                                                                }
                                                            </>
                                    }
                                </Form.Item>
                        }
                    </Fragment>
                ))
            }
            {
                isMainCountModal && <HomePage_ModalComponent width={500} change_cancel={change_mainCountModalCancel} contentComponent={<HomePage_ModalComponent_ConfirmationModallComponent title="确认要修改吗？" content="编辑主变台数时，被删除的主变如果已设置为监测主变、接地点、地图默认显示主变或安装主变等，对应信息将同步清空，是否确认修改？" operation="修改" operationBgc="#FF4D4F" sourceData={{ type: "mainCount" }} change_cancel={change_mainCountModalCancel} />} />
            }
        </Form>
    )
}

export default HomePage_ModalComponent_NormalFormComponent